<template>
  <div class="login-bg">
    <!-- :style="{height:contentHei}" -->
    <div class="login-content" :style="{ height: contentHei, width: contentWidth }">
      <div class="logo-wrap">
        <div class="logo-bg">
          <img :src="loginLogo" alt="" @error="hideLoginLogo()" v-if="showLoginLogo" />
        </div>
        <div class="langWrap">
          <!-- <Button size="small" type="dashed" @click="changeLang" style="color:#3d52c9;font-size: 18px;">{{this.langText}}</Button> -->
        </div>
      </div>
      <div class="content-wrap">
        <Form style="width: 500px">
          <div style="height: 65px">
            <div class="input-icon-wrap">
              <input
                  @input="inputName"
                  type="text"
                  :placeholder="$t('enterusername')"
                  class="login-input"
                  v-model.trim="loginForm.username"
              />
              <img
                  style="width: 17px;height: 19px;"
                  :src="userNameIcon"
                  alt="username"
                  class="input-icon"
              />
            </div>
            <div class="line" v-show="validate.user"></div>
            <div v-show="!validate.user">
              <div class="line2"></div>
              <div style="color: red;font-size: 14px;margin-top: 5px">
                {{ validate.userPrompt }}
              </div>
            </div>
          </div>
          <div style="height: 65px">
            <div class="input-icon-wrap">
              <input
                  @input="inputPWD"
                  :type="loginForm.passwordInputType"
                  :placeholder="$t('enterpassword')"
                  v-model.trim="loginForm.password"
                  class="login-input"
              />
              <img
                  style="width: 17px;cursor: pointer;height: 19px;"
                  :src="pwdIcon"
                  @click="showPassword"
                  alt="username"
                  class="input-icon"
              />
            </div>
            <div class="line" v-show="validate.pwd"></div>
            <div v-show="!validate.pwd">
              <div class="line2"></div>
              <div style="color: red;font-size: 14px;margin-top: 5px">{{ validate.pwdPrompt }}</div>
            </div>
          </div>
          <div style="height: 90px">
            <div style="display: flex;justify-content: flex-start;align-items: center">
              <input
                  @input="inputYZM"
                  type="text"
                  :placeholder="$t('Verificationcode')"
                  class="login-input"
                  v-model.trim="loginForm.captcha"
              />
              <img
                  style="width: 17px;height: 19px;"
                  :src="codeIcon"
                  alt="username"
                  class="input-icon"
              />
              <img
                  class="yzm-img"
                  :src="yzmPic"
                  :alt="$t('Verificationcode')"
                  :title="$t('updateverificationcode')"
                  @click="verification"
              />
            </div>
            <div class="line" v-show="validate.yzm"></div>
            <div v-show="!validate.yzm">
              <div class="line2"></div>
              <div style="color: red;font-size: 14px;margin-top: 5px">{{ validate.yzmPrompt }}</div>
            </div>
          </div>
          <div style="height: 65px" id="login-box">
            <Checkbox
                size="large"
                v-model="remerberToken"
                style="color:#3d52c9;font-weight: bold"
            >{{ $t('rememberMe') }}</Checkbox
            >
          </div>
          <div class="login-btn-wrap">
            <Button type="info" class="login-btn" @click="loginButton" :loading="loginLoading">{{
                $t('capitalLogin')
              }}</Button>
          </div>
        </Form>
      </div>
    </div>
  </div>
</template>

<script>
import encryption from '@/libs/encryption.js';
import cookieUse from '@/libs/cookie.js';
import { login, verCode, baseInfo, getLogoImg, queryLogoImg } from '@/api/login.js';
import { mapMutations,mapActions,mapState } from 'vuex';
export default {
  data() {
    return {
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      validate: {
        user: true,
        userPrompt: '',
        pwd: true,
        pwdPrompt: '',
        yzm: true,
        yzmPrompt: ''
      },
      remerberToken: true,
      btnLoading: false,
      // yzmPic: '',
      loginForm: {
        passwordInputType: 'password',
        username: '',
        password: '',
        captcha: '',
        t: '',
        key: '',
        salt: '',
        iv: ''
      },
      // 显示的语言
      langText: '',
      // 验证
      line1: false,
      // icon
      userNameIcon: require('../../assets/login/login-username.png'),
      pwdIcon: require('../../assets/login/login-pwd.png'),
      codeIcon: require('../../assets/login/login-code.png'),
      defYzm: require('../../assets/login/defYzm.png'),
      // 设置宽高
      contentWidth: '',
      contentHei: '',
      //logo
      loginLogo: '',
      showLoginLogo: true,
      logoList: []
    };
  },
  computed:{
    ...mapState('login',['t','key','salt','iv','loginLoading']),
    yzmPic(){
      if(this.t){
        return `${this.baseURL}/identity/anonymity/captcha?t=${this.t}`
      }else{
        return this.defYzm;
      }
    }
  },
  watch:{
    t(val){
      this.loginForm.captcha = '';
    }
  },
  methods: {
    ...mapMutations(['setProjectName']),
    ...mapActions('login',['verification']),
    // 设置样式
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      if (this.fullWidth <= 1450) {
        this.contentWidth = '761px';
        this.contentHei = '540px';
      } else if (this.fullWidth > 1450 && this.fullWidth <= 1800) {
        this.contentWidth = '817px';
        this.contentHei = '580px';
      } else if (this.fullWidth > 1800 && this.fullWidth < 2100) {
        this.contentWidth = '890px';
        this.contentHei = '630px';
      } else {
        this.contentWidth = '1152px';
        this.contentHei = '816px';
      }
    },
    // 验证码
    // verification() {
    //   let _this = this;
    //   verCode()
    //     .then((res) => {
    //       if (res.data.code === 1) {
    //         let getData = res.data.data;
    //         let codeArr = [];
    //         for (let key in getData) {
    //           codeArr.push(getData[key]);
    //         }
    //         codeArr.sort();
    //         const t = getData['t'];
    //         const key = codeArr[0];
    //         const salt = codeArr[1];
    //         const iv = codeArr[2];
    //         _this.loginForm.t = t;
    //         _this.loginForm.key = key;
    //         _this.loginForm.salt = salt;
    //         _this.loginForm.iv = iv;
    //         _this.yzmPic = `${this.baseURL}/identity/anonymity/captcha?t=${t}`;
    //         _this.loginForm.captcha = '';
    //       } else {
    //         _this.yzmPic = _this.defYzm;
    //       }
    //     })
    //     .catch((err) => {
    //       _this.yzmPic = _this.defYzm;
    //       console.log(err);
    //     });
    // },
    inputName() {
      let userName = this.loginForm.username;
      this.validate.user = true;
      this.userNameIcon = require('../../assets/login/login-username-fource.png');
      if (!userName) {
        this.validate.user = false;
        this.validate.userPrompt = '用户名不能为空';
        this.userNameIcon = require('../../assets/login/login-username.png');
      }
    },
    inputPWD() {
      this.validate.pwd = true;
      let userName = this.loginForm.password;
      this.pwdIcon = require('../../assets/login/login-pwd-fource.png');
      if (!userName) {
        this.validate.pwd = false;
        this.validate.pwdPrompt = '密码不能为空';
        this.pwdIcon = require('../../assets/login/login-pwd.png');
      }
    },
    inputYZM() {
      this.validate.yzm = true;
      let userName = this.loginForm.captcha;
      if (userName.length == 5) {
        this.codeIcon = require('../../assets/login/login-code-fource.png');
      } else {
        this.codeIcon = require('../../assets/login/login-code.png');
      }
      if (!userName) {
        this.validate.yzm = false;
        this.validate.yzmPrompt = '请输入验证码';
        this.codeIcon = require('../../assets/login/login-code.png');
      }
    },
    // 点击显示密码
    showPassword() {
      if (this.loginForm.passwordInputType === 'text') {
        this.loginForm.passwordInputType = 'password';
      } else {
        this.loginForm.passwordInputType = 'text';
      }
    },
    // 用户登录
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        this.loginButton();
      }
    },
    // 登录
    loginButton() {
      let _this = this;
      // _this.btnLoading = true;
      this.$store.commit('login/setLoginLoading',true);
      this.inputName();
      this.inputPWD();
      this.inputYZM();
      function trimStr(str) {
        return str.replace(/(^\s*)|(\s*$)/g, '');
      }
      let UserName = trimStr(this.loginForm.username);
      let PassWord = trimStr(this.loginForm.password);
      let key = encryption.CryptoJS.enc.Utf8.parse(this.key);
      let iv = encryption.CryptoJS.enc.Utf8.parse(this.iv);
      let salt = encryption.CryptoJS.enc.Utf8.parse(this.salt);
      PassWord = encryption.Encrypt(PassWord, key, iv, salt);
      let params = {
        password: PassWord,
        username: UserName,
        rememberMe: this.remerberToken,
        t: this.t,
        captcha: this.loginForm.captcha
      };
      if (this.validate.user && this.validate.pwd && this.validate.yzm) {
        login(JSON.stringify(params))
        .then((res) => {
          if (res.data.code === 1) {
            let token = res.data.data;
            let langModel = 'zh';
            if (this.langText === 'English') {
              langModel = 'zh';
            } else {
              langModel = 'en';
            }
            if (this.remerberToken) {
              cookieUse.setCookie('desig-token', token, 168);
              cookieUse.setCookie('desig-lang', langModel, 168);
              cookieUse.setCookie('Authorization', token, 168);
            } else {
              cookieUse.setCookie('desig-token', token, 8);
              cookieUse.setCookie('desig-lang', langModel, 8);
              cookieUse.setCookie('Authorization', token, 8);
            }
            // this.getUserInfo()
            localStorage.setItem('token', token); // 为topo页面存储
            // 是否记住密码
            sessionStorage.setItem('desig-rm', this.remerberToken);
            this.setProjectName('14');
            this.$router.push({
              path: '/main'
            });
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
            // 更新验证码
            this.verification();
            this.$store.commit('login/setLoginLoading',false)
          }
        })
        .catch((err) => {
          console.log(err);
          this.verification();
          this.$store.commit('login/setLoginLoading',false);
        });
      } else {
        // _this.btnLoading = false;
        this.$store.commit('login/setLoginLoading',false);
      }
    },
    // 切换语言
    // changeLang(){
    //     let val = ''
    //     if(this.langText === '中文'){
    //         val = 'zh'
    //         this.langText = 'English'
    //     }else {
    //         val = 'en'
    //         this.langText = '中文'
    //     }
    //     this.$i18n.locale = val
    //     cookieUse.setCookie('language-s',val)
    //     window.location.reload()
    // },
    // 获取用户信息
    getUserInfo() {
      let _this = this;
      baseInfo()
      .then((res) => {
        if (res.data.code === 1) {
          let userId = res.data.data.id;
          let nickname = res.data.data.nickname;
          let companyName = res.data.data.companyName;
          let companyId = res.data.data.companyId;
          let initPwd = res.data.data.initialPassword;
          let avatar = res.data.data.avatar || require('@/assets/globalIcon/defult.jpg');
          let userName = res.data.data.username;
          let type = res.data.data.type;
          let role = res.data.data.role;
          // 单位管理员或者单位设计师
          let isRootDesigner;
          if (res.data.data.role && res.data.data.role === 'leader') {
            isRootDesigner = true;
          } else {
            isRootDesigner = false;
          }
          let November = {
            userId: userId,
            userName: userName,
            nickname: nickname,
            companyName: companyName,
            companyId: companyId,
            initPwd: initPwd,
            avatar: avatar,
            isRootDesigner: isRootDesigner,
            isReferee: role === 'referee' ? true : false,
            distributed: res.data.data.distributed
          };
          sessionStorage.setItem('November', encryption.SelfUseEncrypt(JSON.stringify(November)));
          _this.$router.push({
            path: '/main'
          });
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 3
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
    },
    hideLoginLogo() {
      this.showLoginLogo = false;
    },
    // 获取系统浏览器标签的图标
    getLogo() {
      let params = {
        logoType: 'bottom',
        systemType: 'designer'
      };
      getLogoImg(params)
      .then((res) => {
        if (res.data.code === 1) {
          // this.loginLogo = '/files'+res.data.data[0].logo
          let getData = res.data.data;
          let bottom = getData.find((item) => item.logoType == 'bottom');
          bottom && (this.loginLogo = '/files' + bottom.logo);
          // this.loginLogo = this.getBottom(getData, this.logoList, 'bottom')
        }
      })
      .catch((err) => {
        console.log(err);
      });
    },
    // 获取数据
    queryLogoImg() {
      let params = {
        logoType: 'bottom',
        systemType: 'designer'
      };
      queryLogoImg(params)
      .then((res) => {
        if (res.data.code == 1) {
          this.logoList = res.data.data;
          console.log('queryLogoImg ~ this.logoList:', this.logoList);
        } else {
          console.log('获取数据失败');
        }
      })
      .catch((errer) => {
        console.log('获取数据失败');
      });
    },
    getBottom(data1, data2, type) {
      let img = '';
      if (data1.length > 0 || data2.length > 0) {
        let logoType1 = data1.filter((d) => d.logoType == type); // 运维设计
        let logoType2 = data2.filter((d) => d.logoType == type); // 单位设计
        if (logoType1.length > 0 && logoType2.length > 0) {
          if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
            img = '/files' + logoType1[0].logo;
          } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo;
          } else if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          } else {
            img = '';
          }
        } else if (logoType1.length > 0 && logoType2.length == 0) {
          if (logoType1[0].hidden == 'enable') {
            img = '/files' + logoType1[0].logo;
          }
        } else if (logoType1.length == 0 && logoType2.length > 0) {
          if (logoType2[0].hidden == 'enable') {
            img = '/files' + logoType2[0].logo;
          }
        }
      } else {
        img = '';
      }
      return img;
    },
    getName(data1, data2, type) {
      let name = '';
      let logoType1 = data1.filter((d) => d.logoType == type); // 运维设计
      let logoType2 = data2.filter((d) => d.logoType == type); // 单位设计

      if (logoType1.length > 0 && logoType2.length > 0) {
        if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else if (logoType1[0].hidden == 'enable' && logoType2[0].hidden == 'disable') {
          name = logoType1[0].sysName;
        } else if (logoType1[0].hidden == 'disable' && logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName;
        } else if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else {
          name = '';
        }
      } else if (logoType1.length > 0 && logoType2.length == 0) {
        if (logoType1[0].hidden == 'enable') {
          name = logoType1[0].sysName;
        } else {
          name = '';
        }
      } else if (logoType1.length == 0 && logoType2.length > 0) {
        if (logoType2[0].hidden == 'enable') {
          name = logoType2[0].sysName;
        } else {
          name = '';
        }
      } else {
        name = '';
      }
      return name;
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  mounted() {
    // 项目
    this.$store.commit('login/setLoginLoading',false)
    this.setProjectName('');
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
    let getToken = cookieUse.getCookie('desig-token') || '';
    let getLang = cookieUse.getCookie('language-s') || 'zh';
    if (getLang === 'zh') {
      this.langText = 'English';
    } else {
      this.langText = '中文';
    }
    this.getLogo();
    this.$i18n.locale = getLang;
    window.onresize = () => {
      this.setStyle();
    };
    if (getToken) {
      localStorage.setItem('token', getToken); // 为topo页面存储
      this.$router.push({
        path: '/main'
      });
      // this.getUserInfo()
    } else {
      // 设置样式
      this.setStyle();
      // 验证码
      this.verification();
    }
    // this.loginLogo = `${this.baseURL}/sdn/sys/menu/sysImage?sysType=2&label=3`
  },
  created() {
    // this.queryLogoImg()
  }
};
</script>

<style scoped>
/* @import url("https://fonts.googleapis.com/css?family=Raleway:400,400i,700"); */
.login-bg {
  width: 100%;
  height: 100%;
  background: url('~@/assets/login/loginBg.png') no-repeat center center;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.login-content {
  /* background-color: #fff; */
  /* border-radius: 20px; */
  /* box-shadow: 0px 20px 10px rgba(102,102,102,0.1);  */
  padding: 100px 0 30px 0;
  background: url('../../assets/login/content-bg.png') no-repeat center center;
  background-size: 100% 100%;
}
.logo-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 40px;
}
.logo-bg {
  height: 51px;
  width: 124px;
  /*background: url("../../assets/login/logo-bg.png") no-repeat center center;*/
  /*background-size: 100% 100%;*/
}
.logo-bg img {
  display: inline-block;
  width: 100%;
  height: 100%;
}
.langWrap {
  margin: -15px 0 0 15px;
}
.content-wrap {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  margin-top: 25px;
}
.line {
  width: 100%;
  height: 1px;
  background-color: rgb(113, 57, 47);
  margin-top: 10px;
}
.line2 {
  width: 100%;
  height: 1px;
  background-color: #6a0c1a;
  margin-top: 10px;
}
.input-icon {
  vertical-align: middle;
  margin-left: 10px;
}
.input-icon-wrap {
  display: flex;
  justify-content: space-between;
  padding-right: 5px;
}
.login-btn-wrap {
  display: flex;
  justify-content: center;
}
.login-input {
  width: 90%;
  outline: 0px;
  outline-offset: 0px;
  color: #3d52c9;
  font-size: 16px;
  padding-left: 5px;
  border-width: 0px;
  font-weight: bold;
}
.login-input:focus {
  outline: 0px;
  outline-offset: 0px;
}
.login-input::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: rgb(222, 212, 233);
  font-size: 16px;
  padding-left: 8px;
}
.login-input::-moz-placeholder {
  /* Firefox 19+ */
  color: rgb(222, 212, 233);
  font-size: 16px;
  padding-left: 8px;
}
.login-input:-ms-input-placeholder {
  /* IE 10+ */
  color: rgb(222, 212, 233);
  font-size: 16px;
  padding-left: 8px;
}
.login-input:-moz-placeholder {
  /* Firefox 18- */
  color: rgb(222, 212, 233);
  font-size: 16px;
  padding-left: 8px;
}
.yzm-img {
  height: 45px;
  margin-left: 10px;
  cursor: pointer;
}
.login-btn {
  width: 150px;
  height: 50px;
  font-size: 18px;
  background-color: #273ba8;
  border-radius: 30px;
}
.login-btn:hover {
  background-color: #273ba8;
  box-shadow: 0 0 5px 0 #6273d2;
}
.langWrap .ivu-btn-dashed:hover {
  border-color: #3d52c9;
}
</style>

<style>
#login-box .ivu-checkbox-inner {
  background-color: #3d52c9;
  border: 1px solid rgb(91, 54, 194);
}
#login-box .ivu-checkbox-checked .ivu-checkbox-inner::after {
  /* border-color: #4466d2; */
}
.login-btn-wrap .ivu-btn-info {
  border-color: #3d52c9;
}
</style>
